import React, { Component, PureComponent, useRef } from 'react';
import { StyleSheet, Text, View, Button, DeviceEventEmitter, ScrollView, Alert } from 'react-native';
import styles from 'src/styles';

const Child = (props) => {
  const { myRef, onCancel } = props;
  console.log('CHILD - ', myRef, onCancel);
  myRef.current = {
    onShow: () => {
      Alert.alert('我是子组件', '子组件的方法被父组件调用');
      console.log(myRef);
    }
  }

  return (
    <View style={{ borderWidth: 1, borderColor: '#ded', margin: 10 }}>
      <Text>Child Component</Text>
      <Button onPress={() => { onCancel() }} title='子组件调用父组件的函数' />
    </View>
  );
}

function Home1({ navigation }) {
  // console.log('Home1: ', navigation);
  const child = useRef();

  const handleCancel = (e) => {
    Alert.alert('我是父组件', '父组件的方法被子组件调用');
  }

  const childClick = (e) => {
    child.current.onShow();
  }

  return (
    <View style={styles.container1}>
      <ScrollView style={{ margin: 10 }}>
        <Text>父组件/子组件的调用方法</Text>
        <View style={{ borderWidth: 1, borderColor: '#dad', margin: 10 }}>
          <Text>Parent Component</Text>
          <Child myRef={child} onCancel={handleCancel}></Child>
          <Button onPress={childClick} title='调用子组件的函数' />
        </View>
        <View>
          <Text style={{ fontSize: 20, fontWeight: 'bold' }}>ref是关键字？自定义组件不能使用</Text>
        </View>
      </ScrollView>
      {/* <Button title='Go Home' onPress={() => { navigation.navigate('home') }} />
      <Button title='Go Other' onPress={() => { navigation.navigate('other') }} /> */}
    </View>
  )
}

export default Home1;
